// pages/publish/publish.js
import api from '../../config/api'
import { shareOptions } from '../../utils/access'
import request from '../../utils/request'
import { getStorage, setStorage } from "../../utils/utils"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    images:'',
    nickName:'',
    task:0,
    taskImages:[
    'https://image-classify.daieco.com/kejian-quanzi/HMIcdR7ay1T9d6f54fe6c457e0e1a6e1004b7d4c70a9.png',
    'https://image-classify.daieco.com/kejian-quanzi/95y96bYT2Ad0f3b47b44e8ce102186d4a528dddca716.png'
    ],
    selectText:'选择圈子',
    selectId:'',
    selectIndex: 0,
    objectArray: [],
    text:'',
    picNumber:0,
    imgUrl:'',//拍照任务完成后传的图片链接
    garbageType:2,
    //话题列表
    topicList:[],
    topicSelectIndex: 0,
    // 是否无已加入的圈子
    hadNoCircle: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.circleId){
      this.setData({
        selectId: +options.circleId
      })
      this.getTopicList()
    }
    this.getCircleHasIn()

    if(options.task){
      this.setData({
        task:options.task
      })
      this.getNumber(options.task)
    }
    //完成拍照任务发帖
    if(options.imgUrl){
      this.setData({
        imgUrl:options.imgUrl,
        garbageType:options.garbageType
      })
    }

    //获取上次未发送的文字
    let lastText = getStorage('publishText')
    let lastImage = getStorage('publishImage')
    this.setData({
      nickName:getStorage('userInfo').nickName,
      text:lastText,
      imageList: lastImage || [],
      images: lastImage ? lastImage.join(',') : '',
    })
  },
  // 获取话题数据
 async getTopicList(){
    let res= await request.get(api.circleTopicList,{
      id: this.data.selectId
    },{ loading: false})
    if(res.httpStatus === 200 ){
      this.setData({
        topicSelectIndex: 0,
        topicList: res?.data
      })
    }
  },
  // 选择话题
  selTopic(e){
    let index= e.currentTarget.dataset.index
    this.setData({
       topicSelectIndex: index
    })
  },
  //获取答题或者拍照次数
  getNumber: async function(shareType){
    const res = await request.get(api.getNumberBeforePublish,{shareType})
    if(res.httpStatus==200){
      this.setData({
        picNumber:res.data
      })
    }
  },
  //获取已经加入的圈子
  getCircleHasIn: async function(){
    const { selectId } = this.data
    const res = await request.get(api.getCircleListAdded)
    console.log('res', res);
    if(res?.data?.length > 0){
      if(selectId){ //如果有选择的圈子id
        this.setData({
          objectArray: res.data || [],
          ...((selectId && res?.data?.length) ? {
            selectText: res.data.find((f) => f.id === selectId)?.title,
            selectIndex: res.data.findIndex((f) => f.id === selectId)
          } : {})
        })
      }else{ // 没有选择圈子id就默认选中成员最多的圈子
       this.setData({
          objectArray: res.data || [],
       })
       if(res?.data?.length){
        let circleNum=0
        res.data.forEach(item=>{
           if(item.circleNum>circleNum){
            circleNum= item.circleNum
           }
        })
        let selectId=res.data.find((f) => f.circleNum === circleNum)?.id
        let selectText=res.data.find((f) => f.circleNum === circleNum)?.title
        let selectIndex=res.data.findIndex((f) => f.circleNum === circleNum)
        this.setData({
          objectArray: res.data || [],
          selectId,
          selectText,
          selectIndex
       })
       this.getTopicList()
       }
      }
    }else{
      this.setData({
        hadNoCircle: true
      })
      this.getDefaultCircle()
    }
  },
  // 加入圈子
  async addCircle(){
    let { selectId } = this.data
    const res= await request.post(api.circleAdd + '/' + selectId, null, { loading: false, modal: false })
    if (res.httpStatus === 200) {
    }
  },
  // 获取默认圈子列表
  async getDefaultCircle(){
    const { selectId } = this.data
    const res = await request.get(api.defaultCricle)
    if(res?.data){
      this.setData({
        objectArray: res.data || [],
      })
      if(res?.data?.length){
        let circleNum=0
        res.data.forEach(item=>{
          if(item.circleNum>circleNum){
            circleNum= item.circleNum
          }
        })
        let selectId=res.data.find((f) => f.circleNum === circleNum)?.id
        let selectText=res.data.find((f) => f.circleNum === circleNum)?.title
        let selectIndex=res.data.findIndex((f) => f.circleNum === circleNum)
        this.setData({
          objectArray: res.data || [],
          selectId,
          selectText,
          selectIndex
        })
        this.getTopicList()
      }
    }
  },
  onInputChange:function(e){
    // console.log('e',e.detail.value);
    this.setData({
      text: e.detail.value
    })
    setStorage('publishText', e.detail.value)
  },
  //选择圈子
  bindPickerChange:function(e){
    let index = e.detail.value
    let data = this.data.objectArray
    this.setData({
      selectText: data[index].title,
      selectId: data[index].id,
      selectIndex: index
    })
    this.getTopicList()
  },
  // 图片是否在上传中
  getImageLoading(e) {
    this.imageLoading = e.detail
  },
  //获取上传后的图片
  getRecycleImage:function(e){
    console.log('图片地址',e)
    let list = e.detail.list
    this.setData({
      images:list.join(',')
    })
    setStorage('publishImage', list)
  },
  // 跳转到圈子列表
  jumpCircleList(){
    this.isCircleListBack= true
    wx.navigateTo({
      url: '/pages/circleList/circleList',
    })
  },
  //发表
  submit: async function(){
    const {text,selectId,images,task,picNumber,taskImages,imgUrl,garbageType,topicList,topicSelectIndex,hadNoCircle} = this.data
    if(text.length<5){
      wx.showToast({
        title: '最少五个字',
        icon: 'none'
      })
      return
    }
    if(selectId==''){
      wx.showToast({
        title: '请选择圈子',
        icon: 'none'
      })
      return
    }
    if (this.imageLoading) {
      wx.showToast({
        title: '图片正在上传中',
        icon: 'none'
      })
      return
    }
    if (this.loading) return
    this.loading = true
    let arr = []
    if(images.length>0){
      arr = images.split(',')
    }else if(task!==0){
      //完成拍照任务或者答题任务上传固定的背景图片
      arr.push(task==2?taskImages[1]:taskImages[0])
      if(imgUrl!==''){
        arr.push(imgUrl)
      }
    } 

    console.log('帖子图片：', arr);
    let params={
      circleId:selectId,
      content:text,
      picUrls:arr,
      shareType:task==2?garbageType:task,
      extend:picNumber
    }
    if(topicList.length>0){
      params.topicId= topicList[topicSelectIndex].id
    }
    const res = await request.post(api.addDynamic,params)
    if(res.httpStatus==200){
      setStorage('publishText', '')
      setStorage('publishImage', [])
      wx.showToast({
        title: '发布成功',
        icon: 'none'
      })
      if(hadNoCircle){
        this.addCircle()
      }
      this.publishSuccess = true
      setTimeout(()=>{
        wx.navigateBack({
          delta: 1,
          complete: () => {
            this.loading = false
          }
        })
      },800)
    } else {
      this.publishSuccess = false
      this.loading = false
    }
    console.log('添加', res);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.publishSuccess = false
     // 圈子列表返回过来刷新已加入圈子数据
     if(this.isCircleListBack){
        this.getCircleHasIn()
        this.isCircleListBack= false
     }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.updatePrePage()
  },
  /**
   * 更新父级页面帖子数据
   */
  updatePrePage() {
    const pages = getCurrentPages()
    const prePage = pages[pages.length - 2]
    if ([
      'pages/circle/circle',
      'pages/circleHome/circleHome'
    ].includes(prePage?.route) && !this.publishSuccess) {
      prePage.isFromPublish = false
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.updatePrePage()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 用户点击右上角分享
	onShareAppMessage(e) {
    return shareOptions('default', e)
	},
})